#include "QUncoverFaceOperation.h"

#include "Core/MainWindow.h"
#include "Core/RWGeometryTool.h"
#include <QMessageBox>
#include "FeatureShape/ShapeOperation.h"
#include "FeatureShape/HistoryManager.h"
#include <TopoDS.hxx>

QUncoverFaceOperation::QUncoverFaceOperation(MainWindow* inMainWindow, ShapeOperation* inOperation, QWidget* parent)
	: QRSWidgetBase(inMainWindow, inOperation, parent)
	, ui(new Ui::QUncoverFaceOperationClass())
{
	ui->setupUi(this);

	m_mainWindow->SetCanMultiSelect(false);

	connect(ui->modifyButton, &QPushButton::clicked, this, &QUncoverFaceOperation::OnModify);
	connect(ui->confirmButton, &QPushButton::clicked, this, &QUncoverFaceOperation::OnConfirm);
	connect(ui->cancelButton, &QPushButton::clicked, this, &QUncoverFaceOperation::close);

	connect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QUncoverFaceOperation::OnSelectedSubShapes);

	m_mainWindow->SetSelectionMode(SM_Face);
}

QUncoverFaceOperation::~QUncoverFaceOperation()
{
	delete ui;
}

void QUncoverFaceOperation::OnSelectedSubShapes(QIVtkSelectionPipeline* actor)
{
	if (actor)
	{
		m_selectedActor = actor;
	}
}

void QUncoverFaceOperation::closeEvent(QCloseEvent* event)
{
	disconnect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QUncoverFaceOperation::OnSelectedSubShapes);

	m_mainWindow->SubWidgetClose(bIsConfirmed);
	m_mainWindow->SetCanMultiSelect(true);
}

void QUncoverFaceOperation::OnModify()
{
	UncoverInner();
	m_selectedActor = nullptr;
}

void QUncoverFaceOperation::OnConfirm()
{
	UncoverInner();
	close();
}

void QUncoverFaceOperation::UncoverInner()
{
	if (!m_selectedActor)
	{
		QMessageBox::warning(this, tr("Warning"), tr("Please select a valid shape."));
		return;
	}

	TopoDS_Face face = TopoDS::Face(m_mainWindow->GetSelectedShapes()[0]);
	TopoDS_Shape remain = RemoveFaceAndKeepBoundary(m_selectedActor->OccShape(), face);

	int shapeIndex = GetIndexFromActor(m_mainWindow->GetCachedActors(), m_selectedActor);
	int subShapeIndex = GetSubShapeIndex(m_selectedActor->OccShape(), TopAbs_FACE, face);

	UncoverFaceOperation* op = new UncoverFaceOperation(QString("Uncover Face"), shapeIndex, subShapeIndex);
	m_mainWindow->GetHistoryManager()->applyOperation(op);

	m_mainWindow->RemoveActorFromRenderer(m_selectedActor);
	m_mainWindow->createBasicUnitActor(remain, true);
}
